package com.woniuxy.lab.woniu_lab.service.impl;
import java.time.LocalDateTime;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.lab.woniu_lab.controller.form.AddCommentForm;
import com.woniuxy.lab.woniu_lab.model.Comment;
import com.woniuxy.lab.woniu_lab.dao.CommentDao;
import com.woniuxy.lab.woniu_lab.model.Range;
import com.woniuxy.lab.woniu_lab.model.User;
import com.woniuxy.lab.woniu_lab.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.lab.woniu_lab.service.RangeService;
import com.woniuxy.lab.woniu_lab.service.UserService;
import com.woniuxy.lab.woniu_lab.service.dto.CommentDto;
import com.woniuxy.lab.woniu_lab.service.dto.ParentCommentDto;
import com.woniuxy.lab.woniu_lab.util.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author Silas
 * @since 2023-03-15
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentDao, Comment> implements CommentService {
    public static final String CHECKED = "CHECKED";
    public static final String UNCHECK = "UNCHECK";
    @Resource
    private CommentDao commentDao;
    @Resource
    private RangeService rangeService;
    @Resource
    private UserService userService;

    @Override
    public IPage<CommentDto> findComment(Integer userId, Integer page, Integer size) {
        IPage<Comment> iPage = new Page<>(page == null ? 1 : page, size == null ? 4 : size);
//        IPage<Comment> page1 = commentDao.selectPage(iPage, new QueryWrapper<Comment>());
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<Comment>().eq("user_id", userId)
                .eq("parent_id", 0);
        List<Comment> comments = commentDao.selectList(queryWrapper);
        List<Comment> commentList = new ArrayList<>();
        for (Comment comment : comments) {
            Integer parentId = comment.getId();
            List<Comment> comments1 = commentDao.selectList(new QueryWrapper<Comment>().eq("parent_id", parentId).eq("checked", "UNCHECK"));
            commentList.addAll(comments1);
        }
        iPage.setRecords(commentList);
        iPage.setTotal(commentList.size());
        IPage<CommentDto> commentDtoIPage = iPage.convert(u -> {
            CommentDto commentDto = new CommentDto();
            BeanUtils.copyProperties(u, commentDto);
            return commentDto;
        });
        return commentDtoIPage;
    }

    @Override
    public List<ParentCommentDto> queryComment(Integer rangeId) {
        List<Comment> comments =list(new QueryWrapper<Comment>().eq("range_id", rangeId));
        //无评论
        if (comments==null||comments.size()==0){
            return null;
        }
        List<Comment> parents = new ArrayList<>();
        for (Comment comment : comments) {
            //一级评论
            if (comment.getParentId()==0){
                parents.add(comment);
            }
        }
        //一级评论集合转化为parentCommentDto
        List<ParentCommentDto> parentCommentDtos = BeanUtil.copyToList(parents, ParentCommentDto.class);
        //将所有评论转为commentDto
        List<CommentDto> commentDtos = BeanUtil.copyToList(comments, CommentDto.class);
        //循环一级评论
        for (ParentCommentDto parentCommentDto : parentCommentDtos) {
            //取出一级评论中的子评论集合
            List<CommentDto> comments1 = parentCommentDto.getComments();
            //循环所有评论
            for (CommentDto comment : commentDtos) {
                //子找父
                if (comment.getParentId().equals(parentCommentDto.getId())){
                    if (comments1==null||comments1.size()== 0){
                        comments1 = new ArrayList<>();
                    }
                        comments1.add(comment);

                }
            }
            //二级评论写入一级评论
            parentCommentDto.setComments(comments1);
        }
        return parentCommentDtos;
    }

    @Override
    public void addComment(AddCommentForm addComment) {
        Integer userId = JwtUtil.getUserIdFromReq();
        Range range = rangeService.getById(addComment.getRangeId());
        User user = userService.getById(userId);

        if (addComment.getParentId()==0){
            //一级评论直接写入
            saveComment(addComment, range, user,0);

        }else{
            //子评论
            saveComment(addComment, range, user,addComment.getParentId());
        }
    }

    /**
     * 新增评论或者回复
     * @param addComment 评论内容及评论对象
     * @param range 靶场ID
     * @param user 用户
     * @param parentId 一级评论ID
     */
    private void saveComment(AddCommentForm addComment, Range range, User user,Integer parentId) {
        Comment comment = new Comment();
        comment.setUserId(user.getId());
        comment.setTeacherId(range.getTeacherId());
        comment.setRangeId(range.getId());
        comment.setParentId(parentId);
        comment.setContent(addComment.getContent());
        comment.setCommentTime(LocalDateTime.now());
        comment.setNickName(user.getNickname());
        comment.setUserPic(user.getPic());
        comment.setChecked(UNCHECK);

        save(comment);
    }

    @Override
    public void read(Integer commentId) {
        Comment comment = getById(commentId);
        comment.setChecked(CHECKED);
        updateById(comment);
    }
}
